<?php
uses('model');

class shopcarModel extends Model {

    function __construct() {
        parent::__construct();
    }

    //购物车列表
    function shopCarList($v) {
        $this->dbconnect();

        $where = $v['sessionid'] ? "sessionid='{$v['sessionid']}'" : '1';

        if ($v['admin']) {
            if ($v['pagesize']) {
                $data['list'] = $this->db->GetPage(array($this->table['shopcar']." a LEFT JOIN {$this->table['users']} b ON a.uid = b.id", 'a.*, b.username', $where.($v['sort'] ? " ORDER BY {$v['sort']} {$v['sortorder']}" : '')), $data['page'], $v['pagesize']);
            } else {
                $data['list'] = $this->db->GetAll($this->table['shopcar']." a LEFT JOIN {$this->table['users']} b ON a.uid = b.id", 'a.*, b.username', $where.($v['sort'] ? " ORDER BY {$v['sort']}" : ''));
            }
        } else {
            $data['list'] = $this->db->GetAll($this->table['shopcar']." a LEFT JOIN {$this->table['items']} b ON a.iid=b.id", 'a.*, b.model', $where.($v['sort'] ? " ORDER BY {$v['sort']}" : ''));
        }

        foreach ($data['list'] as $v) {
            $data['totalamount'] += $v['amount'];
            $data['totalprice'] += $v['price'] * $v['amount'];
        }

        return $data;
    }

    //购物车更新
    function shopCarUpdate($v) {
        $this->dbconnect();

        /*
        8.购物的数量大于库存
        */

        if (isset($v['id']) && isset($v['amount']) || $v['emptycar']) {
            if ($v['emptycar']) {
                $this->db->Delete($this->table['shopcar'], "sessionid='{$v['sessionid']}'");
            } else {
                $fields['amount'] = abs($v['amount']);

                //检查库存是否足够
                $row = $this->db->GetRow($this->table['shopcar'].' a LEFT JOIN '.$this->table['items'].' b ON a.iid=b.id', 'a.amount, b.stocknum, b.postfee', "a.id={$v['id']}"); //取得库存数量和额外运费
                if ($fields['amount'] > $row['stocknum']) {
                    $fields['amount'] = ($row['stocknum'] > 0 ? $row['stocknum'] : 0);
                    $data['code']['shopCarUpdate'] = 8;
                }
                $fields['postfee'] = $fields['amount'] * $row['postfee'];
                if ($row['amount'] != $fields['amount']) $this->db->Update($this->table['shopcar'], $fields, "id={$v['id']} AND sessionid='{$v['sessionid']}'");
            }
        } else {
            //检查购物车中所有物品库存是否足够
            $shopcars = $this->db->GetAll($this->table['shopcar'], 'id,amount', "sessionid='{$v['sessionid']}'");
            foreach ($shopcars as $shopcar) {
                $shopcar['sessionid'] = $v['sessionid'];
                $r = $this->shopCarUpdate($shopcar);
                if ($r['code']['shopCarUpdate'] == 8) $data = 8;
            }
        }

        return $data ? $data : true;
    }

    //清理 1.数量为0的 2.库存为0的
    function shopCarClear() {
        $this->dbconnect();

        return $this->db->Delete($this->table['shopcar'], "amount=0");
    }

    //结帐
    function checkout($v) {
        $this->dbconnect();

        //新地址
        if (!$v['linkman'] && $v['paddr']) {
            $fields = $this->db->GetRow($this->table['address'], 'address,tel,linkman,zipcode', "id={$v['paddr']} AND uid={$v['uid']}");
        } else {
            $fields['linkman']  = $v['linkman'];
            $fields['address']  = $v['address'];
            $fields['tel']      = $v['tel'];
            $fields['zipcode']  = $v['zipcode'];
        }

        //订单概要
        $items = $this->db->GetAll($this->table['shopcar'], 'iid,iname,amount,price', "sessionid='{$v['sessionid']}'");

        //取得成本价
        foreach ($items as $_v) $_iid[] = $_v['iid'];
        $_iid = join(',', $_iid);
        $tmp = $this->db->GetAll($this->table['items'], 'id,pricein', "id IN($_iid)");
        foreach ($tmp as $_v) $pricein[$_v['id']] = $_v['pricein'];

        //取得返点数
        $backpoint = $this->db->GetOne($this->table['shopcar'].' a LEFT JOIN '.$this->table['items'].' b ON a.iid = b.id', 'sum((b.price1-b.price3)*a.amount)', "sessionid='{$v['sessionid']}' AND b.price3");

        $fields['sid']      = $v['sessionid'];
        $fields['uid']      = $v['uid'];
        $fields['data']     = serialize($items);
        $fields['memo']     = $v['memo'];
        $fields['sumfee']   = $this->db->GetOne($this->table['shopcar'], "SUM(amount*price)", "sessionid='{$v['sessionid']}'");
        $fields['postfee']  = $v['postfee'];
        $fields['posttype'] = $v['posttype'];
        $fields['created']  = time();
        $fields['updated']  = time();

        $fields['cman']     = $v['cman'];
        $fields['cphone']   = $v['cphone'];
        $fields['cemail']   = $v['cemail'];

        //返点
        $fields['camefrom'] = $v['camefrom'];
        $fields['backpoint']= intval($backpoint);

        //包装
        $fields['needpack'] = $v['needpack'];

        //meta
        if ($v['meta']) $fields['meta'] = serialize($v['meta']);

        if ($v['adjustfee'])    $fields['adjustfee']= $v['adjustfee'];
        if ($v['log'])          $fields['log']      = $v['log'];

        $data['code']['checkout'] = $this->db->Insert($this->table['indent'], $fields) ? 1 : 2;

        //清空购物车，记录订单详情
        if ($data['code']['checkout'] == 1) {
            if ($lastid = $this->db->Insertid()) {
                foreach ($items as $item) {
                    $item['idid']       = $lastid;
                    $item['cost']       = $pricein[$item['iid']]; //成本
                    $item['updated']    = time();

                    //记录到详情表
                    $this->db->Insert($this->table['indentd'], $item);

                    //减少库存
                    $this->db->Update($this->table['items'], array('stocknum'=>"{[-{$item['amount']}]}"), "id={$item['iid']}");
                }
                $data['indentid'] = $lastid;
            }

            //清理购物车
            $this->db->Delete($this->table['shopcar'], "sessionid='{$v['sessionid']}'");

            //注册会员发 mail
            if ($v['uid'] && $row = $this->db->GetRow($this->table['users'], 'nickname,email', "id={$v['uid']}")) {
                $f['subject']   =   "乐铺 $lastid 号新订单通知 - ".date('Y-m-d H:i');
                $f['mailto']    =   $row['email'];
                $f['body']      =   "亲爱的{$row['nickname']}：\r\n\r\n";
                $f['body']      .=  "感谢您对乐铺的支持并承蒙订购。您的订单号为 {$lastid}，我们会为您订购的产品保留三天的付款期，三天内未付款订单会自动被取消。\r\n\r\n";
                $f['body']      .=  "您还可以随时在乐铺的用户中心中来察看和管理您的订单。\r\n\r\n";
                $f['body']      .=  "如果您是通过线下汇款方式支付，请务必在支付后通知我们，以便乐铺为您第一时间发货。\r\n\r\n";
                $f['body']      .=  "您在付款过程中有任何问题，欢迎随时与我们取得联系，很期待为您服务。\r\n\r\n";
                $f['created']   =   time();
                $this->db->Insert($this->table['mail'], $f);
            }
        }

        return $data;
    }
}
?>
